package com.qf.gh.web.servlet;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

public class BaseServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String res = req.getParameter("method");
        try {
            Method method = this.getClass().getMethod(res, HttpServletRequest.class, HttpServletResponse.class);
            Object invoke = method.invoke(this, req, resp);
            if(invoke == null) {

            } else {
                String  str= invoke.toString();
                if(str.startsWith("redirect:")) {
                    String[] arr = str.split(":");
                    if (arr != null && arr.length > 1) {
                        resp.sendRedirect(arr[1]);
                    }
                } else {
                    String[] arr = str.split(":");
                    if(arr!= null && arr.length > 1){
                        req.getRequestDispatcher(arr[1]).forward(req, resp);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("调用方法失败");
        }
    }
}
